//
//  WaitSendGoodsController.m
//  WuJieLive
//
//  Created by iMac on 2017/12/21.
//  Copyright © 2017年 zhk. All rights reserved.
//

#import "WaitSendGoodsController.h"
#import "OrderDetailController.h"
#import "CancelOrderView.h"
#import "OrderSectionFooterView.h"
#import "MyCollectionViewCell.h"
#import "OrderSectionHeaderView.h"

@interface WaitSendGoodsController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic , strong)UITableView * tableview;
@property (nonatomic , assign) NSInteger index;
@property (nonatomic , strong) NSMutableArray * dataArray;

@property (nonatomic , strong) CancelOrderView * cancelView;
@end

@implementation WaitSendGoodsController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}


-(void)viewWillAppear:(BOOL)animated
{
    [self.tableview.mj_header beginRefreshing];
}

- (void)setUI
{
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:(UITableViewStyleGrouped)];
    [self.view addSubview:self.tableview];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerNib:[UINib nibWithNibName:@"MyCollectionViewCell" bundle:nil] forCellReuseIdentifier:@"MyCollectionViewCell"];
    [self.tableview registerClass:[OrderSectionFooterView class] forHeaderFooterViewReuseIdentifier:@"OrderSectionFooterView"];
    [self.tableview registerClass:[OrderSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"OrderSectionHeaderView"];
    
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
}

- (void)requestData
{
    self.index = 1;
    [self requestMoreData];
}

-(void)requestMoreData
{
    NSDictionary * dict = @{@"token":self.userToken,@"order_status":@"pre_goods",@"page":[NSString stringWithFormat:@"%ld",self.index]};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/index",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        if (isSuccess) {
            if (self.index == 1) {
                self.dataArray = [NSMutableArray array];
            }
            for (int i = 0; i < [responseObject[@"data"] count]; i ++) {
                MyOrderDetailModel * model = [[MyOrderDetailModel alloc]init];
                [model setValuesForKeysWithDictionary:responseObject[@"data"][i]];
                [self.dataArray addObject:model];
            }
            if ([responseObject[@"hasmore"] integerValue] == 0) {
                [self.tableview.mj_footer endRefreshingWithNoMoreData];
            }
            self.index += 1;
            [self.tableview reloadData];
            [self endRefresh];
        }
    } failure:^(NSError *error) {
        [self endRefresh];
    }];
}

- (void)endRefresh
{
    if (self.tableview.mj_header.isRefreshing) {
        [self.tableview.mj_header endRefreshing];
    }else
    {
        [self.tableview.mj_footer endRefreshing];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyOrderDetailModel * model = self.dataArray[indexPath.section];
    OrderDetailController * vc = [[OrderDetailController alloc]init];
    vc.orderID = model.order_id;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    MyOrderDetailModel * model = self.dataArray[section];
    return model.goods.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    OrderSectionHeaderView * view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"OrderSectionHeaderView"];
    MyOrderDetailModel * model = self.dataArray[section];
    [view bindDataWithModel:model];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    OrderSectionFooterView * view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"OrderSectionFooterView"];
    MyOrderDetailModel * model = self.dataArray[section];
    [view bindDataWithModel:model];
    view.rebackBlock = ^{
        [self rebackWithOrderID:model.order_id];
    };
    return view;
}

- (void)rebackWithOrderID:(NSString *)orderID
{
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary * dict = @{@"token":self.userToken};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/request-refund",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            NSArray * reasonsArray = responseObject[@"data"][@"reasons"];
            NSMutableString * headerString = [NSMutableString string];
            for (int i = 0; i < [responseObject[@"data"][@"tips"] count]; i ++) {
                headerString = [headerString stringByAppendingString:[NSString stringWithFormat:@"\n%@",responseObject[@"data"][@"tips"][i]]].mutableCopy;
            }
            
            self.cancelView.backgroundColor = [UIColor clearColor];
            [[UIApplication sharedApplication].keyWindow addSubview:self.cancelView];
            [self.cancelView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.bottom.offset(0);
            }];
            self.cancelView.titleString = @"申请退款";
            self.cancelView.detailTextLabel.text = headerString;
            self.cancelView.dataArray = reasonsArray;
            self.cancelView.doneBlock = ^(NSInteger index) {
                [weakSelf.cancelView removeFromSuperview];
                [weakSelf rebackWithID:orderID andReason:responseObject[@"data"][@"reasons"][index]];
            };
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void)rebackWithID:(NSString *)orderID andReason:(NSString *)reason
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary * dict = @{@"token":self.userToken,@"order_id":orderID,@"cancel_reason":reason};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/request-refund",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            [self requestData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MyCollectionViewCell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = Color(245, 245, 245);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MyOrderDetailModel * model = self.dataArray[indexPath.section];
    OrderListModel * detailModel = [OrderListModel new];
    [detailModel setValuesForKeysWithDictionary:model.goods[indexPath.row]];
    [cell bindDataWithModel:detailModel];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(CancelOrderView *)cancelView
{
    if (!_cancelView) {
        _cancelView = [[[NSBundle mainBundle] loadNibNamed:@"CancelOrderView" owner:self options:nil] lastObject];
        _cancelView.titleString = @"申请退款";
    }
    return _cancelView;
}

@end
